package org.uned.agonzalo16.bitacora.service.comment;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.uned.agonzalo16.bitacora.dao.CommentDao;
import org.uned.agonzalo16.bitacora.domain.Article;
import org.uned.agonzalo16.bitacora.domain.Comment;

@Service("CommentService")
public class CommentService {

	@Autowired
	private CommentDao commentDao;

	public List<CommentTree> createCommentsTree(Article article) {

		Comment falseComment = new Comment();
		falseComment.setId(-1L);
		CommentTree root = new CommentTree(falseComment);

		// para que la creación del árbol funcione los artículos se deben
		// obtener en el orden que se crearon. Para no procesar los nodos hijos
		// antes que los padres
		for (Comment comment : commentDao.findByArticle(article)) {
			if (comment.getParentComment() == null) {
				root.addComment(comment);
			} else {
				CommentTree parent = root.contains(comment.getParentComment());
				if (parent != null) {
					parent.addComment(comment);
				}
			}
		}

		return root.getChildren();
	}
}
